package edu.xmu.software.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

public class UserAuthDAO {
	private JdbcTemplate jdbcTemplate;
	
	public void setDataSource(DataSource dataSource){
		jdbcTemplate = new JdbcTemplate(dataSource);
	}
	
	public boolean isAdmin(String userName){
		Connection connection = null;
		try{
			final String AUTH_SQL = "select * from userauth where username = ?";
			connection = jdbcTemplate.getDataSource().getConnection();
			PreparedStatement queryPs = connection.prepareStatement(AUTH_SQL);
			queryPs.setString(1, userName);
			ResultSet rs = queryPs.executeQuery();
			if (rs.next()){
				int isAdmin;
				isAdmin = rs.getInt("isadmin");
				if(isAdmin == 0)
					return false;
				else return true;
			}
		}catch (SQLException e){
			e.printStackTrace();
		}finally{
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return false;
	}
	public boolean isValid (String userName){
		Connection connection = null;
		try{
			final String VALID_SQL = "select * from userauth where username = ?";
			connection = jdbcTemplate.getDataSource().getConnection();
			PreparedStatement queryPs = connection.prepareStatement(VALID_SQL);
			queryPs.setString(1, userName);
			ResultSet rs = queryPs.executeQuery();
			if (rs.next()){
				int isValid;
				isValid = rs.getInt("isvalid");
				if(isValid == 0)
					return false;
				else return true;
			}
		}catch (SQLException e){
			e.printStackTrace();
		}finally{
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return false;
	}
	public boolean addUserAuth(String userName){
		System.out.println("EEEeee");
		final String INSERT_SQL = "INSERT INTO userauth (username, isvalid, isadmin, canupload, candel) value (?, 1, 0, 1, 1)";
		System.out.println("EEE" + userName);
		Connection connection = null;
		try{
			connection = jdbcTemplate.getDataSource().getConnection();
			PreparedStatement insertPs = connection.prepareStatement(INSERT_SQL);
			insertPs.setString(1, userName);
			insertPs.execute();
			return true;
		}catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return false;
	}
}
